package com.roger.homecenterscreen.config

import android.content.Context
import android.content.SharedPreferences

/**
 * 业务配置（服务端与数字员工）
 * - 支持在应用运行时读取/更新
 * - 用于MQTT连接、语音服务接口、CosyVoice鉴权等
 */
object BusinessConfig {
    private const val PREF_NAME = "business_config"

    // 服务端HTTP地址（用于语音接口，如声纹识别）
    var serverHttpBaseUrl: String = "http://192.168.31.85:8088"

    // 声纹识别接口路径（可与voiceprint01.json保持一致）
    var voiceprintVerifyPath: String = "/api/voiceprint/verify"

    // 数字员工ID
    var dempId: String = "DEMP-0001"

    // MQTT配置
    var mqttHost: String = "192.168.31.85"
    var mqttPort: Int = 1883
    var mqttUseSsl: Boolean = false
    var mqttUsername: String? = "lzwc"
    var mqttPassword: String? = "Lzwc@4187."

    // CosyVoice相关配置
    // 仅使用临时 apikey 进行鉴权；不要在端侧硬编码长效密钥
    // 临时鉴权说明：https://help.aliyun.com/zh/model-studio/obtain-temporary-authentication-token
    var cosyVoiceApiKey: String = "sk-de540095f526466a964bce8c5320c329"
    // CosyVoice 流式 TTS WebSocket 地址（示例默认）
    var cosyVoiceUrl: String = "wss://dashscope.aliyuncs.com/api-ws/v1/inference"
    var cosyVoiceModel: String = "cosyvoice-v2"
    var cosyVoiceVoice: String = "longyingxiao"
    var cosyVoiceFormat: String = "pcm"
    var cosyVoiceSampleRate: Int = 24000

    fun load(context: Context) {
        val sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        serverHttpBaseUrl = sp.getString("serverHttpBaseUrl", serverHttpBaseUrl) ?: serverHttpBaseUrl
        voiceprintVerifyPath = sp.getString("voiceprintVerifyPath", voiceprintVerifyPath) ?: voiceprintVerifyPath
        dempId = sp.getString("dempId", dempId) ?: dempId
        mqttHost = sp.getString("mqttHost", mqttHost) ?: mqttHost
        mqttPort = sp.getInt("mqttPort", mqttPort)
        mqttUseSsl = sp.getBoolean("mqttUseSsl", mqttUseSsl)
        mqttUsername = sp.getString("mqttUsername", mqttUsername)
        mqttPassword = sp.getString("mqttPassword", mqttPassword)
        // 兼容旧键名 cosyVoiceAppKey → 新键名 cosyVoiceApiKey
        val oldAppKey = sp.getString("cosyVoiceAppKey", null)
        val newApiKey = sp.getString("cosyVoiceApiKey", cosyVoiceApiKey)
        cosyVoiceApiKey = (newApiKey ?: oldAppKey ?: cosyVoiceApiKey)

        cosyVoiceUrl = sp.getString("cosyVoiceUrl", cosyVoiceUrl) ?: cosyVoiceUrl
        cosyVoiceModel = sp.getString("cosyVoiceModel", cosyVoiceModel) ?: cosyVoiceModel
        cosyVoiceVoice = sp.getString("cosyVoiceVoice", cosyVoiceVoice) ?: cosyVoiceVoice
        cosyVoiceFormat = sp.getString("cosyVoiceFormat", cosyVoiceFormat) ?: cosyVoiceFormat
        cosyVoiceSampleRate = sp.getInt("cosyVoiceSampleRate", cosyVoiceSampleRate)
    }

    fun update(context: Context, block: (SharedPreferences.Editor) -> Unit) {
        val sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        val editor = sp.edit()
        block(editor)
        editor.apply()
        load(context)
    }
}